from rest_framework import serializers
from .models import User
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings


class CreateUserSerializer(serializers.ModelSerializer):
  rePassword = serializers.CharField(label='确认密码', write_only=True)
  verifyCode = serializers.CharField(label='验证码', write_only=True)

  class Meta:
    model = User
    fields = ['id', 'password', 'rePassword', 'mobile', 'verifyCode', 'email', 'username']
    extra_kwargs = {
      'username': {
        'label': '用户名',
        'min_length': 2,
        'max_length': 20,
        'error_messages': {
          'min_length': '仅允许5-20个字符的用户名',
          'max_length': '仅允许5-20个字符的用户名',
        }
      },
      'password': {
        'write_only': True,
        'min_length': 6,
        'max_length': 20,
        'error_messages': {
          'min_length': '密码仅允许8-20个字符的',
          'max_length': '密码仅允许8-20个字符的',
        }
      }
    }

  def validator_mobile(self, value):
    if not re.match(r'1[3-9]\d{9}$', value):
      raise serializers.ValidationError('手机号码格式有误')
    return value

  def validator_email(self, value):
    if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', value):
      raise serializers.ValidationError('邮箱格式有误')
    return value

  def validate(self, attrs):
    if attrs['password']!=attrs['rePassword']:
      raise serializers.ValidationError('密码不一致')

    redis_conn = get_redis_connection('verify_codes')
    mobile = attrs['mobile']
    real_verify_code = redis_conn.get('verify_%s' % mobile)
    if real_verify_code is None or attrs['verifyCode'] != real_verify_code.decode():
      raise serializers.ValidationError('验证码错误')
    return attrs

  def create(self, validated_data):
    del validated_data['rePassword']
    del validated_data['verifyCode']

    password = validated_data.pop('password')
    user = User(**validated_data)
    user.set_password(password)
    user.save()

    # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    # payload = jwt_payload_handler(user)
    # token = jwt_encode_handler(payload)
    # user.token = token
    return user


class UserInfoSerializer(serializers.ModelSerializer):
  class Meta:
    model = User
    fields = ["id", "mobile", "avatar", "email", "username", "address", "gender", "motto", "bgWall"]
